<?php
	session_start();
	
	define('CRMURL', 'http://localhost:8000');
	define('LOGPATH','F:\\obj\\output\\lbg\\CRM\\static\\log\\');
	
	date_default_timezone_set("Etc/GMT-8");
	ini_set('max_execution_time',3000);
	error_reporting(E_ERROR);
	include_once 'function.php';
	$fun = getRequest('callback');
	//exit(retjson(1,$_SESSION['username'],$fun));
	/*  跨域问题后面解决
	if(empty($_SESSION['username'] )){
		exit(retjson(0,'unlogin', $fun));
	}
	*/
	$username = getRequest('senduser');
	$mailgroupid = getRequest('groupid');
	$sendgroup = getRequest('sendgroup');
	$delaytime = getRequest('delay',0)*1000;
	$content = urldecode(getRequest('content'));
	$subject = urldecode(getRequest('obj'));
	if(empty($content) || empty($subject)||empty($mailgroupid)){
		exit(retjson(0,'Content not null!',$fun));
	}
	if(empty($username)){
		exit(retjson(0,'unlogin', $fun));
	}
	$_SESSION['username'] = !empty($username)?$username:'undefined';

	$conn = mysql_connect('localhost','root','');
	mysql_select_db('admin_crm');
	mysql_query('set names utf8');
	//初始化fromEmail当天发送数为0
	$sql = 'update `crm_smtpsendermaillist` set `daytimes`=0 where `senddate`<>"'.date('Y-m-d',time()).'"';
	mysql_query($sql);
	//得到接收邮件清单
	$sql = 'select `mail_sendmail` mail,`user_name` name from `crm_smtpsendmalilist` where `send_state` in (2,3) and  `mailgroup_id` in ('.$mailgroupid.')';
	$ret = @mysql_query($sql);
	$maillist = array();
	$i=0;
	while ($row = @mysql_fetch_array($ret)){
		$maillist[$i]['name'] = $row['name'];
		$maillist[$i++]['mail'] = $row['mail'];
	}
	if(count($maillist)<1){
		exit(retjson(0,'Email Group No Emails!',$fun));
	}
	//插入发送记录
	$sql = 'insert into `crm_smtplog` values("","'.$mailgroupid.'","'.$subject.'","'.addslashes($content).'","'.$_SESSION['username'].'",now(),0)';
	@mysql_query($sql);
	$send_id = mysql_insert_id();
	$sendret = doGroupSending($maillist,$subject,$content,$send_id,$sendgroup,$delaytime);
	mysql_close($conn);
	//var_dump($sendret);
	exit($sendret);
?>